package com.lyh.servlet;

import com.lyh.pojo.Book;
import com.lyh.pojo.Category;
import com.lyh.service.BookService;
import com.lyh.service.CategoryService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 功能
 * 作者：lyh
 * 日期：2024/8/8 13:13
 */
@WebServlet("/add")
@MultipartConfig //解析二进制表单
public class AddBook extends HttpServlet {
    CategoryService categoryService = new CategoryService();
    BookService bookService = new BookService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.查询所有类别信息
        List<Category> categoryList = categoryService.findAllTypes();
        //2.保存到request域
        request.setAttribute("categoryList",categoryList);
        //3.转发到添加界面
        request.getRequestDispatcher("/jsp/addBook.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.接收表单数据
        String bname = request.getParameter("bname");
        String author = request.getParameter("author");
        String num = request.getParameter("num");
        String price = request.getParameter("price");
        String cid = request.getParameter("cid");

        String page = "demo1.jpg";
        Part file2 = request.getPart("file1");
        //文件名称 保证名称不重复
        if (file2.getSize()>0){
            //获取当前时间的毫秒值
            page = System.currentTimeMillis()+".jpg";
            // new Date().getTime()
//            Calendar.getInstance().getTimeInMillis();
            //获取项目的输出目录 指定上传路径
            String realPath = getServletContext().getRealPath("/static/img");
            //执行上传操作
            file2.write(realPath+"/"+page);
        }
        //2.调用业务层方法完成添加
        bookService.addBook(new Book(null,bname,author,Integer.parseInt(num),page,Double.parseDouble(price),Integer.parseInt(cid)));
        //3.做出响应 重定向-》图书展示
        response.sendRedirect(request.getContextPath()+"/show");
    }
}
